package com.example.javademo.filter;

import com.example.javademo.Utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

//@WebFilter("/*")
public class DemoFilter implements Filter {
//    每次拦截到请求都会触发
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    System.out.println("DemoFilter");
        System.out.println("放行后");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        if(req.getRequestURI().contains("/login")||req.getRequestURI().contains("/regist")||req.getRequestURI().contains(".html")||req.getRequestURI().contains("doc")||req.getRequestURI().contains("swagger")){
            chain.doFilter(request,response);
            System.out.println(req.getRequestURI()+"放行后");
            return;
        }
        String token =  req.getHeader("token");
        System.out.println("token:"+token);
        if(token==null){
            res.setStatus(401);
            return;
        }
        System.out.println("需要校验的接口");
        try {

         Object claims = JwtUtils.parseToken(token);
         System.out.println(claims +"claims");
         if(claims!=null){
             chain.doFilter(request,response);
             System.out.println(req.getRequestURI()+"放行后");
         }
        }catch (Exception e){
            res.setStatus(401);
        }
    }
    @Override
    public void destroy() {
        System.out.println("destroy");
        Filter.super.destroy();


    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
//        Filter.super.init(filterConfig);
    }
}
